package com.ruoyi.web.controller.business;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.DtoUser;
import com.ruoyi.system.domain.dto.DtoVehicle;
import com.ruoyi.system.domain.vo.ScreenVo;
import com.ruoyi.system.domain.vo.VoUser;
import com.ruoyi.system.domain.vo.VoVehicle;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 大屏信息Controller
 * 
 * @author ruoyi
 * @date 2024-05-09
 */
@RestController
@RequestMapping("/business/screen")
public class TbScreenController extends BaseController
{
    @Autowired
    private ITbScreenService tbScreenService;
    @Autowired
    private ITbVisitorUserService tbVisitorUserService;
    @Autowired
    private ITbVisitorVehicleService vehicleService;

    @Autowired
    private ITbOutGoodService tbOutGoodService;

    @Autowired
    private ITbGoodsService tbGoodsService;
    private static final Logger log = LoggerFactory.getLogger(TbScreenController.class);
    /**
     * 查询大屏信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:screen:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbScreen tbScreen)
    {
        startPage();
        List<TbScreen> list = tbScreenService.selectTbScreenList(tbScreen);
        return getDataTable(list);
    }

    /**
     * 导出大屏信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:screen:export')")
    @Log(title = "大屏信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbScreen tbScreen)
    {
        List<TbScreen> list = tbScreenService.selectTbScreenList(tbScreen);
        ExcelUtil<TbScreen> util = new ExcelUtil<TbScreen>(TbScreen.class);
        util.exportExcel(response, list, "大屏信息数据");
    }

    /**
     * 获取大屏信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:screen:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbScreenService.selectTbScreenById(id));
    }

    /**
     * 新增大屏信息
     */
    @PreAuthorize("@ss.hasPermi('system:screen:add')")
    @Log(title = "大屏信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbScreen tbScreen)
    {
        return toAjax(tbScreenService.insertTbScreen(tbScreen));
    }

    /**
     * 修改大屏信息
     */
    @PreAuthorize("@ss.hasPermi('system:screen:edit')")
    @Log(title = "大屏信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbScreen tbScreen)
    {
        return toAjax(tbScreenService.updateTbScreen(tbScreen));
    }

    /**
     * 删除大屏信息
     */
    @PreAuthorize("@ss.hasPermi('system:screen:remove')")
    @Log(title = "大屏信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbScreenService.deleteTbScreenByIds(ids));
    }

    /**
     * 获取大屏信息详细信息
     */
    @GetMapping(value = "/now")
    public AjaxResult getNowInfo()
    {
        ScreenVo vo = new ScreenVo();

        TbScreen tbScreen = tbScreenService.selectTbScreenById(100L);
        BeanUtils.copyProperties(tbScreen, vo);

        Long pid = tbScreen.getPid();

        if (pid !=null && pid.intValue() != 0) {
            QrConfig config = new QrConfig(240, 240);
            String qrJpg = QrCodeUtil.generateAsBase64("http://ps.jhm.com.cn/uploadImg?id="+String.valueOf(tbScreen.getPid()), config, "jpg");
            vo.setQr(qrJpg);

            // 过磅物品
            TbOutGood outGoods = new TbOutGood();
            outGoods.setPid(tbScreen.getPid());
            outGoods.setFlag("1");
            List<TbOutGood> outGoodslist = tbOutGoodService.selectTbOutGoodList(outGoods);
            if (outGoodslist != null && outGoodslist.size() > 0) {
                int length = outGoodslist.size();
                String img = "";
                for (int i = 0; i<length; i++) {
                    img = img + outGoodslist.get(i).getImage();
                    if (i != length -1) {
                        img = img + ",";
                    }
                }
                vo.setOutGoodList(img);
            }

            // 携带物品
            TbGoods goods = new TbGoods();
            goods.setPid(pid);
            List<TbGoods> goodsList = tbGoodsService.selectTbGoodsList(goods);
            if (!goodsList.isEmpty()) {
                List<String> goodImgs = new ArrayList<String>();
                for (TbGoods item : goodsList) {
                    if (StringUtils.isNotBlank(item.getPhoto())) {
                        String[] imgs = item.getPhoto().split(",");
                        if (imgs != null && imgs.length > 0) {
                            for (String img : imgs) {
                                goodImgs.add(img);
                            }
                        }
                    }
                }
                vo.setCarryList(goodImgs);
            } else {
                vo.setCarryList(new ArrayList<String>());
            }

        } else {
            vo.setQr("");
            vo.setOutGoodList("");
            vo.setCarryList(new ArrayList<String>());
        }

        if (StringUtils.isNotBlank(vo.getVehiclesPercentage())) {
            vo.setVehiclesPercentageSu(new BigDecimal(vo.getVehiclesPercentage()));
        }
        if (StringUtils.isNotBlank(vo.getVisitedPercentage())) {
            vo.setVisitedPercentageSu(new BigDecimal(vo.getVisitedPercentage()));
        }

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());

        DtoUser tbVisitorUser = new DtoUser();
        tbVisitorUser.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        tbVisitorUser.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));

        // 访客列表
        List<TbVisitorUser> uList = tbVisitorUserService.selectTbVisitorUserList(tbVisitorUser);
        List<VoUser> userList = new ArrayList<VoUser>();
        for (TbVisitorUser user : uList) {
            VoUser voUser = new VoUser();
            voUser.setUserName(user.getUserName());
            Date inTime = user.getInTime();
            voUser.setInTime(inTime);
            if (inTime.compareTo(DateUtils.getNowDate()) <= 0) {
                voUser.setStatusName("已到访");
            } else {
                voUser.setStatusName("未到访");
            }
            userList.add(voUser);
        }
        vo.setUserList(userList);

        // 车辆列表
        DtoVehicle tbVisitorVehicle = new DtoVehicle();
        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        tbVisitorVehicle.setInTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));
        List<TbVisitorVehicle> vlist = vehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        List<VoVehicle> vehicleList = new ArrayList<VoVehicle>();
        for (TbVisitorVehicle vehicle : vlist) {
            VoVehicle voVehicle = new VoVehicle();
            voVehicle.setUserName(vehicle.getCard());
            voVehicle.setInTime(vehicle.getInTime());
            String status = vehicle.getStatus();
            if ("4".equals(status) || "5".equals(status)) {
                voVehicle.setStatusName("已到访");
            } else {
                voVehicle.setStatusName("未到访");
            }
            vehicleList.add(voVehicle);
        }
        vo.setVehicleList(vehicleList);



        return success(vo);
    }

    /**
     * 获取大屏信息详细信息
     */
    @GetMapping(value = "/sound")
    public AjaxResult getSound()
    {

        log.debug("-----------getSound-1-----------");
        TbScreen tbScreen = tbScreenService.selectTbScreenById(100L);
        String card = tbScreen.getNumberplate();

//        String text = vehicleService.textToSpeech(card);

        log.debug("-----------getSound-2-----------");
        return AjaxResult.success("OK", "");

//        try {
//            File audioFile = new File(text);
//            FileInputStream inputStream = new FileInputStream(audioFile);
//
//            byte[] buffer = new byte[(int) audioFile.length()];
//            inputStream.read(buffer);
//
//            inputStream.close();
//
//            // 设置响应的内容类型为音频类型
//            response.setContentType("audio/mp3");
//
//            // 获取响应的输出流
//            ServletOutputStream outputStream = response.getOutputStream();
//            outputStream.write(buffer);
//            outputStream.flush();
//            outputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
